package com.cn.yz.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
	
	// 缺省应用名
	private static final String DEFAULT_PATH = "/";
	
	//字符集
	private static final String CHARACTER_SET = "utf-8";

	/**
	 * 添加Cookie
	 * 
	 * @param name
	 * @param value
	 * @param response
	 * @param age
	 * @throws Exception
	 */
	public static void addCookie(String name, String value, HttpServletResponse response, int age) throws Exception {
		// 创建一个cookie对象,处理编码问题
		Cookie cookie = new Cookie(name, URLEncoder.encode(value, CHARACTER_SET));
		// 设置它的有效路径
		cookie.setPath(DEFAULT_PATH);
		// 设置它的有效时间
		cookie.setMaxAge(age);
		// 发送cookie
		response.addCookie(cookie);
	}

	/**
	 * 查找cookie对象
	 * 
	 * @param name
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String findCookie(String name, HttpServletRequest request) throws UnsupportedEncodingException {
		String value = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie curr = cookies[i];
				if (curr.getName().equals(name)) {
					value = URLDecoder.decode(curr.getValue(), CHARACTER_SET);
				}
			}
		}
		return value;
	}

	/**
	 * 删除cookie对象
	 * 
	 * @param name
	 * @param response
	 */
	public static void deleteCookie(String name, HttpServletResponse response, String domain) {
		Cookie cookie = new Cookie(name, null);
		cookie.setMaxAge(-1);
		cookie.setDomain(domain);
		cookie.setPath(DEFAULT_PATH);
		response.addCookie(cookie);
	}
}
